<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加角色</title>

    <link rel="stylesheet" href="/static/layui/css/layui.css">

</head>

<body style="padding: 10px;">
<form class="layui-form">

    <!-- 角色名称 -->
    <div class="layui-form-item">
        <label class="layui-form-label">角色名称</label>
        <div class="layui-input-inline">
            <input type="text" name="name" required lay-verify="required" placeholder="请输入角色名称" autocomplete="off"
                   class="layui-input">
        </div>
    </div>

    <!-- 权限树 -->
    <div class="layui-form-item">
        <label class="layui-form-label">权限</label>
        <div class="layui-input-inline">
            <div id="menus-tree"></div>
        </div>
    </div>


    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formSubmit">提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>


<script src="/static/layui/layui.js"></script>
<script>
    layui.use(['layer', 'form', 'tree'], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form;
        var tree = layui.tree;


        //渲染tree
        var menusTree = tree.render({
            elem: '#menus-tree',   //绑定元素
            id: 'menusTreeId', //定义索引
            showCheckbox: true, //多选框
            accordion: true, //手风琴效果
            // data: menudata, //数据
            data: <?php echo $menus;?>
    })
        ;


        //监听提交
        form.on('submit(formSubmit)', function (data) {
            //获得选中的节点
            var checkedMenu = tree.getChecked('menusTreeId');
            // console.log({title:data.field.title, powers: JSON.stringify(checkedMenu)});
            $.post('/admin/role/save', {name: data.field.name, powers: checkedMenu}, function (res) {
                if (res.code == '200') {
                    layer.msg('添加成功', {
                        icon: 6,
                        time: 500
                    }, function () {
                        parent.window.location.reload();
                    });
                } else {
                    layer.msg(res.msg, {
                        icon: 5,
                        time: 1000
                    });
                }
            }, 'json');

            return false;
        });
    });

</script>
</body>

</html>